<template>
<div class="chartContainer">
    <div class="search-container">
            <el-form-item label="搜索图表：" >
                <el-input
                        v-model="search"
                        class="w-50 m-2"
                        size="large"
                        placeholder="图表名称 / 图表类型 / 分析目标"
                        :prefix-icon="Search"
                        :clearable="true"
                        @change="doSearch"
                        @clear="clearSearch"
                />
                <el-button style="margin-left: 10px" @click="getChartDataList2()">重置</el-button>
            </el-form-item>
    </div>
   <div class="card-container">
       <el-skeleton animated :rows="2" :loading="loading">
       <el-empty :description="description" v-if="chartDataList.length === 0"></el-empty>
       <el-card class="box-card" style="--el-card-padding: 0 15px;" v-show="(chartDataList.length > 0)" v-for="chartData in chartDataList" :key="chartData.id">
           <el-scrollbar height="500px" :noresize="true">
               <div class="text item" >
                   <div class="chartHead">
                     <span style="display:inline-block;margin-bottom: 5px;font-size: 13.5px">图表名称：{{chartData.name}}</span>
                     <el-button type="danger" size="small" style="position: absolute;right: 5px" @click="deleteChart(chartData.id)">删除</el-button>
                     <br/>
                     <span style="font-size: 13.5px;">分析目标：{{chartData.goal}}</span>
<!--                     <span style="font-size: 13.5px;">用户：{{chartData.goal}}</span>-->

                   </div>
                   <v-chart id="displayChart" :option="parseGenChart(chartData.genchart)" @click="showOriginData"></v-chart>
                   <div class="chartResult">
                       <el-collapse>
                           <el-collapse-item title="分析结论（点击查看）">
                              {{chartData.getResult}}
                           </el-collapse-item>
                       </el-collapse>
                   </div>
               </div>
            </el-scrollbar>
       </el-card>
       </el-skeleton>
   </div>
    <div v-if="!(chartDataList.length === 0)" style="margin: 20px 0;display: flex;justify-content: center">
        <el-pagination
            @current-change="getCurrentPageNum"
            background layout="prev, pager, next"
            :total="totalPageNum"
            v-model:current-page="currentPage"
        />
    </div>
</div>
</template>

<!--图表列表-->

<script setup>
import {onMounted, ref} from 'vue'
import { Search } from '@element-plus/icons-vue'
import * as echarts from 'echarts';
import myAxios from "../../../plugins/myAxios.js";
import {ElMessage} from "element-plus";
import { useRoute} from "vue-router";

const route  = useRoute();

const search = ref('')


const chartDataList = ref([]);//数据list
const loading = ref(true); //骨架屏loading
const description = ref("暂无数据")
const pageSize = 10; //每页获取多少条数据
const currentPage = ref(1);

const totalPageNum = ref(0); //总页数

/**
 * 处理eCharts option配置项
 * @param genChart
 * @returns {any}
 */
const parseGenChart = (genChart) => {
  if(genChart === undefined || genChart === null){
    return {};
  }
  try {
    let json = JSON.parse(genChart)
    if(Object.keys(json).includes('grid')){
      delete json.grid;
    }
    if(!Object.keys(json).includes('toolbox')){
      json.toolbox ={};
    }
    json.toolbox ={
      show:true,
      feature:{
        dataView:{
          readOnly:false
        },
        dataZoom:{},
        magicType:{
          type: ['line','bar']
        },
        restore:{},
        saveAsImage:{}
      }
    }
    if(json.hasOwnProperty("title")){
      if(json.title.hasOwnProperty("text"))
        json.title.text = "";
    }
    return json;
  } catch (e) {
    return {};
  }
}

/**
 * 搜索框搜索
 * @returns {Promise<void>}
 */
const doSearch =async ()=>{
    loading.value = true;

    if(search.value === null || search.value === ' '){
        return;
    }
    const res = await myAxios.post('/chart/my/list/search',{
        name:search.value,
        goal:search.value,
        chartType:search.value,
       current:currentPage.value,
       pageSize:pageSize.value
    })
    if (res.code === 0 && res.data) {
        chartDataList.value = res.data.records;
      totalPageNum.value = parseInt(res.data.total);
      currentPage.value = parseInt(res.data.current);
        loading.value = false;
        if(chartDataList.value.length === 0){
            description.value = '未搜索到数据'
        }
    }else{
        loading.value = false;
        ElMessage.error("请求数据错误")
    }
}
const clearSearch = ()=>{
    console.log(search.value)
}


//点击图表后显示原始数据
const showOriginData = ()=>{
    alert("asda")
}

/**
 * 需要在跳转到这个页面的时候就需要请求一次数据，将数据渲染在页面上。
 * @returns {Promise<void>}
 */

//进入组件获取初始数据
onMounted(()=>{
  initGetChartDataList();
})

const initGetChartDataList = async ()=>{
  description.value = '暂无数据'
  const res = await myAxios.post('/chart/my/list/page',{
    current:currentPage.value,
    pageSize:pageSize.value
  })
  if (res.code === 0 && res.data) {
    chartDataList.value = res.data.records;
    totalPageNum.value = parseInt(res.data.total);
    currentPage.value = parseInt(res.data.current);
    loading.value = false;
  }else{
    loading.value = false;
    ElMessage.error("请求数据错误")
  }
}



//第一次获取数据
const getChartDataList2 = async ()=>{
  if(search.value.trim() === ''){
    ElMessage.warning("请输入搜索关键字")
    loading.value = false;
    return ;
  }
    description.value = '暂无数据'
    const res = await myAxios.post('/chart/my/list/page',{
      current:currentPage.value,
      pageSize:pageSize.value
    })
    if (res.code === 0 && res.data) {
        chartDataList.value = res.data.records;
        totalPageNum.value = parseInt(res.data.total);
        currentPage.value = parseInt(res.data.current);
        loading.value = false;
    }else{
        loading.value = false;
        ElMessage.error("请求数据错误")
    }
}


/**
 * 根据页号获取图表数据
 * @param currentPageNumber
 */
const getCurrentPageNum = (currentPageNumber)=>{
  console.log(`current page: ${currentPageNumber}`)
  currentPage.value = currentPageNumber;
    //每次当点击页号的时候就会发送请求
    getChartDataList()
}

//获取分页图表数据
const getChartDataList = async ()=>{
    //第一次请求不需求传递页面大小和页号，后端有默认为第一页，一页显示6条数据。
    const res = await myAxios.post('/chart/my/list/page',{
      current:currentPage.value,
      pageSize:pageSize.value
    })
    if (res.code === 0 && res.data) {
      console.log(res)
      console.log(chartDataList.value)
        chartDataList.value = res.data.records;
        totalPageNum.value = parseInt(res.data.total);
        currentPage.value = parseInt(res.data.current);
        loading.value = false;
    }else{
        loading.value = false;
        ElMessage.error("请求数据错误")
    }
}

const deleteChart = async (id) => {
  const res = await myAxios.post('/chart/delete',{
    id:id
  })
  if (res.code === 0 && res.data) {
    ElMessage.success("删除成功")
    new Promise(() => {
      getChartDataList()
    })
  }else{
    ElMessage.error("删除失败")
  }
}



</script>

<style scoped lang="less">
@import "src/assets/css/common.less";
.chartContainer{
  overflow: hidden;
  position: relative;
  z-index: 2; /* 确保父div位于子元素之上 */
  .el-input{
    width: 800px;
  }
    .el-input__inner:hover {
        // el-input输入时设置边框颜色
        border: @HoverBlue 1px solid;
    }
  .search-container{
    padding: 10px;
    height: 50px;
    //background: @EleColor;
    //border: solid 1px red;
    position: fixed;
    width: 100%;
    z-index: 100;
  }
  .card-container{
    //border: solid 1px red;
    padding-top: 70px;
    overflow: hidden;
    display: flex;
    justify-content: space-around;
      flex-wrap: wrap;
      .box-card{
          width: 700px;
          height: 500px;
          margin: 20px 0;
          padding: 0;
        opacity: 0.8;
        .text{
          padding: 5px 0 10px 0;
          .chartHead{
            //background: red;
            margin-top: 10px;
            font-size: 15px;
            height: 100px;
            //margin-bottom: 100px;
            span{
              font-size: 13.5px
            }
          }
        }
        .el-card:hover{
          box-shadow: 0 0 7px 0 @HoverBlue;
          transform: translate(-2px,-2px);
        }
          .el-scrollbar{
              //overflow-x: hidden !important;
          }
          #displayChart{
              width: 730px;
              height: 400px;
              padding: 0;
              margin: -30px 0 0 0;
              overflow: hidden;
          }
      }
  }
}
.chartContainer:before {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("../../../assets/img/appearance/bg.png");
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  //opacity: 0.5;
  z-index: -1; /* 将伪元素放置父div下方 */
}
#displayChart{
  margin-top: 20px;
}

</style>